import React, { useState, useEffect, useMemo, useCallback } from 'react';
import { useHistory } from 'react-router-dom';
import './index.scss';
import { Table, Statistic, Empty, Button } from 'antd';
import { calldatainfo, callcount, getTaskList } from 'seats/servers/servers';
import { Line } from '@ant-design/charts';
import { clearNull } from 'utils/tools';
import { ColumnsType } from 'antd/lib/table';
import moment from 'moment';

const HomePage: React.FC = () => {
  const history = useHistory(); //路由对象
  const [timeType, setTimeType] = useState(1); // 时间类型
  const [tableLoaded, setTableLoaded] = useState(false); // 时间类型
  const [chartLoading, setChartLoading] = useState(false); // 时间类型
  const [calldata, setCalldata] = useState<any>({}); // 顶部外呼数据
  const [chartData, setChartData] = useState<any>([]); //chart数据
  const [taskList, setTaskList] = useState<any>([]); // 任务列表

  function isInteger(obj: number) {
    return Math.floor(obj) === obj;
  }

  const getConfig = useMemo(() => {
    // chart数据格式定义
    const config = {
      data: chartData,
      xField: 'date',
      yField: 'value',
      seriesField: 'name',
      yAxis: {
        label: {
          formatter: function formatter(v: any) {
            return isInteger(Number(v)) ? v : '';
          },
        },
      },
      smooth: true,
      animation: {
        appear: {
          animation: 'path-in',
          duration: 1000,
        },
      },
    };
    return config;
  }, [chartData]);

  // table 列定义
  const columns: ColumnsType<any> = [
    {
      title: '序号',
      dataIndex: 'index',
      width: 80,
      render: (text, record, index) => `${index + 1}`,
    },
    {
      title: '任务名称',
      dataIndex: 'taskName',
      width: 200,
      ellipsis: true,
    },
    {
      title: '执行时间段',
      dataIndex: 'allowTimes',
      render: (text: any[], record: any, index: number) => {
        const list = text.map((itm, index2) => (
          <span key={'cell' + index2 + 1}>
            {itm.start}-{itm.end}
          </span>
        ));
        return list;
      },
    },
  ];

  // 点击切换时间类型
  const handleSizeChange = (type: any) => {
    setTimeType(type);
  };

  // 获取统计数据 chart 数据折线图
  const getcallcount = async () => {
    try {
      setChartLoading(true);
      const result = await callcount();
      setChartLoading(false);
      console.log(result);
      if (result.code === 0) {
        const list: any[] = result.data || [];
        let listnew: any[] = [];
        for (const item of list) {
          const l = [
            {
              name: '接通量',
              date: item.date,
              value: item['connectCount'],
            },
            {
              name: '人工介入量',
              date: item['date'],
              value: item['transferManualCount'],
            },
          ];

          listnew = listnew.concat(l);
        }
        setChartData(listnew);
      }
    } catch (e) {
      setChartLoading(false);
    }
  };

  // 获取当日任务列表 4=个
  const getTaskListToday = async () => {
    try {
      setTableLoaded(false);
      const today = moment().format('YYYY-MM-DD');
      const result = await getTaskList(
        clearNull({
          pageNo: 1,
          pageSize: 4,
          taskStatus: '',
          beginTime: today,
          endTime: today,
        })
      );
      console.log(result);
      setTableLoaded(true);
      if (result.code === 0) {
        const list = result.data || [];
        for (const item of list) {
          if (item.allowTimes) {
            item.allowTimes = JSON.parse(item.allowTimes || '[]');
          }
        }
        setTaskList(list);
      }
    } catch (e) {
      setTableLoaded(true);
    }
  };

  // 顶部外呼数据
  const getCalldata = useCallback(async () => {
    console.log('获取顶部外呼数据');
    const result = await calldatainfo({ timeType }); // 外呼数据
    console.log(result);
    if (result.code === 0) {
      setCalldata(result.data);
    }
  }, [timeType]);

  useEffect(() => {
    getCalldata();
  }, [getCalldata]);

  useEffect(() => {
    console.log('渲染useEffect');
    getcallcount();
    getTaskListToday();
  }, []);

  // 跳转到我的任务页面
  const goMytask = () => {
    history.push('/webseats/seats/callTask');
  };

  // 渲染
  return (
    <div className="home-page">
      <div className="waihu-data">
        <div className="title-box">
          <span className="title">外呼数据</span>
          <div className="title-tab">
            <span
              className={timeType === 1 ? 'a1 active' : 'a1'}
              onClick={() => handleSizeChange(1)}
            >
              今天
            </span>
            <span
              className={timeType === 2 ? 'a2 active' : 'a2'}
              onClick={() => handleSizeChange(2)}
            >
              本周
            </span>
            <span
              className={timeType === 3 ? 'a3 active' : 'a3'}
              onClick={() => handleSizeChange(3)}
            >
              本月
            </span>
          </div>
        </div>

        <div className="item-box">
          <div className="item">
            <Statistic
              title="在线时长"
              value={(calldata.onlineDuration || 0) / 60 / 60}
              precision={2}
              suffix="小时"
            />
          </div>
          <div className="item">
            <Statistic
              title="呼叫时长"
              value={(calldata.callDuration || 0) / 60 / 60}
              precision={2}
              suffix="小时"
            />
          </div>
          <div className="item">
            <Statistic
              title="平均通话时长"
              value={(calldata.averageCallDuration || 0) / 60 / 60}
              precision={2}
              suffix="小时"
            />
          </div>

          <div className="item">
            <Statistic title="接通量" value={calldata.connectCount || 0} suffix="个" />
          </div>
          <div className="item">
            <Statistic title="人工介入量" value={calldata.transferManualCount || 0} suffix="个" />
          </div>
          <div className="item">
            <Statistic
              title="人工介入时长"
              value={(calldata.transferManualDuration || 0) / 60 / 60}
              precision={2}
              suffix="小时"
            />
          </div>
        </div>
      </div>

      <section className="section-box">
        <div className="wraper chart-box">
          <div className="title">接通/人工介入量统计</div>
          <div className="chart">
            {/*@ts-ignore*/}
            <Line loading={chartLoading} {...getConfig} />
          </div>
        </div>

        <div className="wraper new-task-box">
          <div className="title">今日新任务</div>
          {taskList.length === 0 && tableLoaded && (
            <Empty description={<span>今天暂无新任务，可以尝试示闲已有任务</span>}>
              <Button onClick={goMytask} type="primary">
                我的任务
              </Button>
            </Empty>
          )}

          {((taskList.length === 0 && !tableLoaded) || taskList.length > 0) && (
            <>
              <Table
                loading={!tableLoaded}
                columns={columns}
                rowKey={record => record.taskId}
                dataSource={taskList}
                pagination={false}
              />
              <div onClick={goMytask} className="go-call">
                马上外呼{'>'}
              </div>
            </>
          )}
        </div>
      </section>
    </div>
  );
};

export default HomePage;
